//
//  SPAppDelegate.m
//  Sophie
//
//  Created by Anton Chebotaev on 4/10/09.
//  Copyright 2009 IFMO. All rights reserved.
//

#import "SPAppDelegate.h"


@implementation SPAppDelegate

#pragma mark NSApplicationDelegate messages
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification {
	// Dock icon still bouncing while this method working
	
	// Load sharedAccount from disk	
	[[SPAccountController sharedController] loadAccountFromDisk];
	[[SPAccountController sharedController] updateFromServer];
	

	// Load preferences from nib to [MBPreferencesController sharedPreferencesController]
	// Preferences should be loaded after all data controlers are initialized and loaded
	SPGeneralPreferencesViewController *generalTab = [[[SPGeneralPreferencesViewController alloc] init] autorelease];
	SPMusicPreferencesViewController *musicTab = [[[SPMusicPreferencesViewController alloc] init] autorelease];
	
	NSArray *modules = [NSArray arrayWithObjects:generalTab, musicTab, nil];
	[[MBPreferencesController sharedController] setModules:modules];	
}

- (void)awakeFromNib {
	// Dock Icon still bouncing while this method working	
}

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
	return [[SPPreferencesController sharedController] shouldCreateDocumentOnStart];
}

- (void)showPreferences:(id)sender
{
	[[MBPreferencesController sharedController] showWindow:sender];	
}

+ (NSString *)getCurrentMusicString {
	NSArray *musicFormat = [[SPPreferencesController sharedController] musicFormat];
	iTunesApplication *iTunes = [[[SBApplication alloc] initWithBundleIdentifier:@"com.apple.iTunes"] autorelease];
	
	if((![iTunes isRunning]) || ([iTunes playerState] != iTunesEPlSPlaying))
	{
		return [NSString string];
	}
	else
	{
		NSMutableString *result = [NSMutableString string];
		iTunesTrack *currentTrack = [iTunes currentTrack];
		
		for (SPMusicFormatToken *token in musicFormat) {
			if([token class] != [SPMusicFormatToken class])
			{
				continue;
			}
			
			if ([token isTitleToken])
			{
				[result appendString:[currentTrack name]];
			}
			else if ([token isAlbumToken])
			{
				[result appendString:[currentTrack album]];
			}
			else if ([token isArtistToken])
			{
				[result appendString:[currentTrack artist]];
			}
			else if ([token isGenreToken])
			{
				[result appendString:[currentTrack genre]];
			}
			else if ([token isRatingToken])
			{
				int stars = [currentTrack rating] / 20;
				for(int i = 0; i < stars; i++)
					[result appendString:@"★"];				
			}
			else
			{
				[result appendString:[token content]];
			}											
		}
		return result;
	}			
}


@end
